#-*- coding: utf8 -*-
#from configparser import BasicInterpolation
import io  
import os
import sys  
import time
import json
import numpy as np

def get_cur_path():
    return os.path.split(os.path.realpath(__file__))[0]

def load_houses(file):
    with open(file, mode='r', encoding='utf-8') as file_obj:
        content = file_obj.read()

    return json.loads(content)

def func():
    house_price_obj = {}
    
    path = r"E:\git_code\LianjiaCrawler\houses\hangzhou"
    url_prefix = "https://hz.lianjia.com/ershoufang/"
    
    files = os.listdir(path)
    for file in files:
        print(file)
        for house_obj in load_houses(path + "\\" + file)["houses"]:
            url = house_obj["u"]
            url = url[url.rfind("/")+1:]
            if url in house_price_obj:
                house_price_obj[url].append(float(house_obj["tp"]))
            else:
                house_price_obj[url] = []
                
    delta_array = []
    for url in house_price_obj:
        tps = house_price_obj[url]
        #tps.sort()
        if len(tps) > 1:
            delta = tps[0] - tps[-1]
            if delta > 0:
                delta_obj = {"url": url_prefix + url, "delta": delta, "old": tps[0], "new": tps[-1]}
                delta_array.append(delta_obj)
            
    delta_array.sort(key=lambda obj: obj["delta"])
    for delta_obj in delta_array:
        print(delta_obj)
        
def find_deal(id):
    path = r"E:\git_code\LianjiaCrawler\houses\wuhan"
    url_prefix = "https://wh.lianjia.com/ershoufang/"
    
    found = False
    files = os.listdir(path)
    for file in reversed(files):
        print(file)
        for house_obj in load_houses(path + "\\" + file)["houses"]:
            url = house_obj["u"]
            #print(url)
            if id in url:
                print(house_obj)
                found = True
                break

        if found:
            break


def collect_price_reduction(city):
    path = "E:\\git_code\\LianjiaCrawler\\houses\\" + city
    files = os.listdir(path)
    
    house_price_map = {}
    for file in files:
        print(file)
        for house_obj in load_houses(path + "\\" + file)["houses"]:
            url = house_obj["u"]
            price = float(house_obj["tp"])
            if not url in house_price_map:
                price_set = set()
                price_set.add(price)
                house_price_map[url] = price_set
            else:
                house_price_map[url].add(price)
                
    house_price_diff_array = []
    for url in house_price_map:
        #print(url)
        min_price = min(house_price_map[url])
        max_price = max(house_price_map[url])
        house_price_diff_array.append((url, max_price-min_price))
        
    house_price_diff_array.sort(key= lambda x:x[1])
    for h_obj in house_price_diff_array[-30:]:
        print(h_obj)
        
if __name__ == '__main__':
    #find_deal("104110739184")
    #sys.exit()
    
    #collect_price_reduction("wuhan")
    #sys.exit()
    
    file1 = os.path.split(os.path.realpath(__file__))[0] + "\\houses\\wuhan\\2025-10-14.json"
    file2 = os.path.split(os.path.realpath(__file__))[0] + "\\houses\\wuhan\\2025-10-29.json"
    file6 = os.path.split(os.path.realpath(__file__))[0] + "\\houses\\wuhan\\2023-08-02.json"

    house_total = 0
    houseMap = {}
    for file in [file1, file2]:
        houses = load_houses(file)
        date = houses["date"]
        house_total = len(houses["houses"])
        for house in houses["houses"]:
            url = house["u"]
            title = house["t"]
            total = float(house["tp"])
            region = house["r"]
            if not url in houseMap:
                houseMap[url] = {"dates": [], "title": "", "region": "", "total_prices": []}
        
            houseMap[url]["dates"].append(date)
            houseMap[url]["title"] = title
            houseMap[url]["region"] = region
            houseMap[url]["total_prices"].append(total)

    change_count = 0
    dec_count = 0
    region_obj = {}

    for url in houseMap:
        if len(houseMap[url]["dates"]) > 1:
            tps = houseMap[url]["total_prices"]
            rgn = houseMap[url]["region"]
            prices_set = set(tps)
            if len(prices_set) > 1:
                print(url, houseMap[url])
                change_count += 1

            aver_tp = np.mean(tps)
            if tps[-1] < aver_tp:
                dec_count += 1
                if rgn in region_obj:
                    region_obj[rgn] += 1
                else:
                    region_obj[rgn] = 1

    print(region_obj)
    print("house_total", house_total)                
    print("change_count", change_count)
    print("dec_count", dec_count)
    print("dec_count/house_total=", dec_count/house_total)
    print("dec_count/change_count=", dec_count/change_count)
    
